/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package visualization;

import allparser.AllFile;
import gov.nasa.worldwind.avlist.AVKey;
import gov.nasa.worldwind.event.RenderingExceptionListener;
import gov.nasa.worldwind.event.SelectListener;
import gov.nasa.worldwind.exception.WWAbsentRequirementException;
import gov.nasa.worldwind.geom.Angle;
import gov.nasa.worldwind.geom.LatLon;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.layers.Layer;
import gov.nasa.worldwind.layers.LayerList;
import gov.nasa.worldwind.layers.RenderableLayer;
import gov.nasa.worldwind.layers.ViewControlsLayer;
import gov.nasa.worldwind.layers.ViewControlsSelectListener;
import gov.nasa.worldwind.render.Polygon;
import gov.nasa.worldwind.util.StatisticsPanel;
import gov.nasa.worldwind.util.WWUtil;
import gov.nasa.worldwindx.examples.ApplicationTemplate;
import gov.nasa.worldwindx.examples.LayerPanel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileFilter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.filechooser.FileNameExtensionFilter;
import oglTest.AllDraw;
import oglTest.oglTest;
import settings.Config;

/**
 *
 * @author Dark Mark
 */
public class AppTemplate extends ApplicationTemplate
{
    private static Dimension canvasSizeZ = new Dimension(800, 640);

    protected static class AppFrameZ extends AppFrame implements ActionListener
    {
        private javax.swing.JMenuBar jMenuBar1;
        private javax.swing.JMenu menuFile;
        private javax.swing.JMenuItem menuOpenFile;
        public static String lastFilePath = "";
        public static String modelLayerName = "Depth Model";
        public static String beamsLayerName = "Beams";
        public static Config config = new Config();
        public static LoadingFrame loadingFrame;
        static JFrame sframe = new JFrame("Animation Tools");
        static oglTest oglframe = null;
        public AllDraw sonar;
        public Ship ship = null;

        public AppFrameZ()
        {
            super(true, true, false);
        }

        public AppFrameZ(boolean includeStatusBar, boolean includeLayerPanel, boolean includeStatsPanel)
        {
            super(includeStatusBar, includeLayerPanel, includeStatsPanel);
        }

        @Override
        protected void initialize(boolean includeStatusBar, boolean includeLayerPanel, boolean includeStatsPanel)
        {
            try
            {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            }
            catch (Exception ex)
            {
            }

            try
            {
                lastFilePath = config.testFilePath;
            }
            catch (Exception ex)
            {
            }

            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

            // menu wyboru pliku
            jMenuBar1 = new javax.swing.JMenuBar();
            menuFile = new javax.swing.JMenu("File");
            menuOpenFile = new javax.swing.JMenuItem("Open...");
            menuOpenFile.addActionListener(this);

            jMenuBar1.add(menuFile);
            menuFile.add(menuOpenFile);
            this.setJMenuBar(jMenuBar1);

            // Create the WorldWindow.
            this.wwjPanel = this.createAppPanel(canvasSizeZ, includeStatusBar);
            this.wwjPanel.setPreferredSize(canvasSizeZ);

            // Put the pieces together.
            this.getContentPane().add(wwjPanel, BorderLayout.CENTER);
            if (includeLayerPanel)
            {
                this.layerPanel = new LayerPanel(this.wwjPanel.getWwd(), null);
                this.getContentPane().add(this.layerPanel, BorderLayout.WEST);
            }

            if (includeStatsPanel || System.getProperty("gov.nasa.worldwind.showStatistics") != null)
            {
                this.statsPanel = new StatisticsPanel(this.wwjPanel.getWwd(), new Dimension(250, canvasSizeZ.height));
                this.getContentPane().add(this.statsPanel, BorderLayout.EAST);
            }

            // Create and install the view controls layer and register a controller for it with the World Window.
            ViewControlsLayer viewControlsLayer = new ViewControlsLayer();
            insertBeforeCompass(getWwd(), viewControlsLayer);
            this.getWwd().addSelectListener(new ViewControlsSelectListener(this.getWwd(), viewControlsLayer));

            // Register a rendering exception listener that's notified when exceptions occur during rendering.
            this.wwjPanel.getWwd().addRenderingExceptionListener(new RenderingExceptionListener()
            {
                public void exceptionThrown(Throwable t)
                {
                    if (t instanceof WWAbsentRequirementException)
                    {
                        String message = "Computer does not meet minimum graphics requirements.\n";
                        message += "Please install up-to-date graphics driver and try again.\n";
                        message += "Reason: " + t.getMessage() + "\n";
                        message += "This program will end when you press OK.";

                        JOptionPane.showMessageDialog(AppFrameZ.this, message, "Unable to Start Program",
                                JOptionPane.ERROR_MESSAGE);
                        System.exit(-1);
                    }
                }
            });

            // Search the layer list for layers that are also select listeners and register them with the World
            // Window. This enables interactive layers to be included without specific knowledge of them here.
            for (Layer layer : this.wwjPanel.getWwd().getModel().getLayers())
            {
                if (layer instanceof SelectListener)
                {
                    this.getWwd().addSelectListener((SelectListener) layer);
                }
            }

            this.pack();

            // Center the application on the screen.
            WWUtil.alignComponent(null, this, AVKey.CENTER);
            this.setResizable(true);
        }

        @Override
        public void actionPerformed(ActionEvent e)
        {
            menuOpenFileActionPerformed(e);
        }

        // wybor pliku wejsciowego
        private void menuOpenFileActionPerformed(java.awt.event.ActionEvent evt)
        {
            JFileChooser jfc = new JFileChooser(lastFilePath);
            FileNameExtensionFilter fileFilter = new FileNameExtensionFilter(".all", "all");
            jfc.addChoosableFileFilter(fileFilter);

            int result = jfc.showOpenDialog(this);
            if (result == JFileChooser.CANCEL_OPTION)
            {
                return;
            }
            lastFilePath = jfc.getSelectedFile().getPath();
            System.out.println(lastFilePath);

            try
            {
                FileWriter fw = new FileWriter(new File("Config.ini"));
                fw.write("testFilePath=" + lastFilePath);
                fw.close();
            }
            catch (Exception e)
            {
            }

            readFile();
        }

        public void readFile()
        {
            if (!lastFilePath.isEmpty())
            {
                try
                {
                    //wywwietlenie ramki otwierajacej
                    loadingFrame = new LoadingFrame();
                    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                    loadingFrame.setLocation(screenSize.width / 2 - 250, screenSize.height / 2 - 150);
                    loadingFrame.setVisible(true);
                    loadingFrame.repaint();

                    //utworzenie wc cache
                    loadingFrame.setTitle("Water Column Cache ...");
                    String[] cmd =
                    {
                        "wcCache.exe"
                    };
                    Process p;
                    try
                    {
                        p = Runtime.getRuntime().exec(cmd);
                        p.waitFor();
                    }
                    catch (Exception ex)
                    {
                    }

                    loadingFrame.setTitle("Depth Data ...");
                    replaceMarkerLayer();

                    loadingFrame.setVisible(false);
                    loadingFrame.dispose();
                }
                catch (Exception e)
                {
                    System.out.println("Problem processing file: " + lastFilePath);
                }
            }
        }

        // metoda aktualizujaca warstwy z modelem glebokosciowym i wiazkami sonaru
        public void replaceMarkerLayer()
        {
            File testFile = new File(lastFilePath);
            if (testFile.canRead())
            {
                try
                {
                    sonar = new AllDraw(0, 9999, lastFilePath);
                    GroundData gData = new GroundData(sonar);

                    //SphereMarkerLayer layer = new SphereMarkerLayer().buildTracksLayer(gData);
                    //layer.setName(modelLayerName);
                    PolyLineLayer polyLineLayer = new PolyLineLayer(gData);
                    polyLineLayer.setName(modelLayerName);
                    replaceLayer(polyLineLayer);

                    BeamsLayer beamsLayer = new BeamsLayer(gData, ship);
                    beamsLayer.setName(beamsLayerName);
                    replaceLayer(beamsLayer);

                    Position newPos = new Position(new LatLon(gData.positions[0][0].latitude, gData.positions[0][0].longitude), getWwd().getView().getEyePosition().getAltitude());
                    getWwd().getView().setEyePosition(newPos);

                    if (oglframe != null)
                    {
                        oglframe.close();
                    }
                    //oglframe = new oglTest(sframe);
                    sonar.path = lastFilePath;
                    oglframe = new oglTest(sframe, ship, gData, this.getWwd());
                    if (sonar == null)
                    {
                        System.out.println("wfail");
                    }
                    else
                    {
                        System.out.println(sonar.datagram68.size());
                    }
                    oglframe.trun(sonar);
                }
                catch (Exception ex)
                {
                    //ex.printStackTrace();
                }
            }
        }

        // metoda sluzaca do dodania/podmiany warstwy
        public void replaceLayer(RenderableLayer layer)
        {
            // usuniecie warstwy, jesli istnieje
            LayerList layers = getWwd().getModel().getLayers();
            for (Layer l : layers)
            {
                if (l.getName().compareToIgnoreCase(layer.getName()) == 0)
                {
                    layers.remove(l);
                }
            }
            // wstawienie nowej warstwy
            insertBeforePlacenames((gov.nasa.worldwind.WorldWindow) this.getWwd(), layer);
            //layers.add(1, layer);
            // aktualizacja listy warstw
            this.getLayerPanel().update(this.getWwd());
        }
    }
}
